package com.lrkj.system.service.impl;

import com.lrkj.common.annotation.DataScope;
import com.lrkj.common.core.domain.TreeSelect;
import com.lrkj.common.core.domain.TreeSelectUp;
import com.lrkj.common.core.domain.entity.OrgTree;
import com.lrkj.common.core.domain.model.LoginUser;
import com.lrkj.common.utils.SecurityUtils;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.system.mapper.OrgTreeMapper;
import com.lrkj.system.service.IOrgTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 组织树Service业务层处理
 *
 * @author yajun_ren
 * @date 2021-07-28
 */
@Service
public class OrgTreeServiceImpl implements IOrgTreeService {
    @Autowired
    private OrgTreeMapper orgTreeMapper;

    /**
     * 查询组织树
     *
     * @param id 组织树ID
     * @return 组织树
     */
    @Override
    public OrgTree selectOrgTreeById(String id) {
        return orgTreeMapper.selectOrgTreeById(id);
    }

    /**
     * 查询组织树列表
     *
     * @param orgTree 组织树
     * @return 组织树
     */
    @Override
    public List<OrgTree> selectOrgTreeList(OrgTree orgTree) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(!loginUser.getUser().isAdmin()){
            orgTree.setNodeId(loginUser.getUser().getDeptId()+"");
        }
        return orgTreeMapper.selectOrgTreeList(orgTree);
    }

    /**
     * 新增组织树
     *
     * @return 结果
     */
    @Override
    public int insertOrgTree(String id, String name, String parentId, String modelType, String ancestors) {
        OrgTree orgTree = new OrgTree();
        orgTree.setId(id);
        orgTree.setName(name);
        orgTree.setParentId(parentId);
        orgTree.setModelType(modelType);
        orgTree.setAncestors(ancestors);
        OrgTree oldBean = orgTreeMapper.selectOrgTreeById(id);
        if (null != oldBean) {
            orgTreeMapper.updateOrgTree(orgTree);
        } else {
            orgTreeMapper.insertOrgTree(orgTree);
        }
        return 1;
    }

    /**
     * 新增组织树
     *
     * @return 结果
     */
    @Override
    public int insertOrgTree(String id, String name, String parentId, String modelType, String ancestors,Integer orderNum) {
        OrgTree orgTree = new OrgTree();
        orgTree.setId(id);
        orgTree.setName(name);
        orgTree.setParentId(parentId);
        orgTree.setModelType(modelType);
        orgTree.setAncestors(ancestors);
        orgTree.setOrderNum(orderNum);
        OrgTree oldBean = orgTreeMapper.selectOrgTreeById(id);
        if (null != oldBean) {
            orgTreeMapper.updateOrgTree(orgTree);
        } else {
            orgTreeMapper.insertOrgTree(orgTree);
        }
        return 1;
    }

    /**
     * 新增组织树
     *
     * @return 结果
     */
    @Override
    public int insertOrgTree(OrgTree orgTree) {
        OrgTree oldBean = orgTreeMapper.selectOrgTreeById(orgTree.getId());
        if (null != oldBean) {
            orgTreeMapper.updateOrgTree(orgTree);
        } else {
            orgTreeMapper.insertOrgTree(orgTree);
        }
        return 1;
    }

    @Override
    public int insertOrgTree(String id, String name, String parentId, String modelType, String ancestors, String ownerName) {
        OrgTree orgTree = new OrgTree();
        orgTree.setId(id);
        orgTree.setName(name);
        orgTree.setParentId(parentId);
        orgTree.setModelType(modelType);
        orgTree.setAncestors(ancestors);
        orgTree.setOwnerName(ownerName);
        OrgTree oldBean = orgTreeMapper.selectOrgTreeById(id);
        if (null != oldBean) {
            orgTreeMapper.updateOrgTree(orgTree);
        } else {
            orgTreeMapper.insertOrgTree(orgTree);
        }
        return 1;
    }

    /**
     * 修改组织树
     *
     * @param orgTree 组织树
     * @return 结果
     */
    @Override
    public int updateOrgTree(OrgTree orgTree) {
        return orgTreeMapper.updateOrgTree(orgTree);
    }

    /**
     * 批量删除组织树
     *
     * @param ids 需要删除的组织树ID
     * @return 结果
     */
    @Override
    public int deleteOrgTreeByIds(String[] ids) {
        return orgTreeMapper.deleteOrgTreeByIds(ids);
    }

    /**
     * 删除组织树信息
     *
     * @param id 组织树ID
     * @return 结果
     */
    @Override
    public int deleteOrgTreeById(String id) {
        return orgTreeMapper.deleteOrgTreeById(id);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelectUp> buildDeptTreeSelect(List<OrgTree> depts) {
        List<OrgTree> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelectUp::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    public List<OrgTree> buildDeptTree(List<OrgTree> depts) {
        List<OrgTree> returnList = new ArrayList<OrgTree>();
        List<String> tempList = new ArrayList<String>();
        for (OrgTree dept : depts) {
            tempList.add(dept.getId());
        }
        for (Iterator<OrgTree> iterator = depts.iterator(); iterator.hasNext(); ) {
            OrgTree dept = (OrgTree) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<OrgTree> list, OrgTree t) {
        // 得到子节点列表
        List<OrgTree> childList = getChildList(list, t);
        t.setChildren(childList);
        for (OrgTree tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<OrgTree> getChildList(List<OrgTree> list, OrgTree t) {
        List<OrgTree> tlist = new ArrayList<OrgTree>();
        Iterator<OrgTree> it = list.iterator();
        while (it.hasNext()) {
            OrgTree n = (OrgTree) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<OrgTree> list, OrgTree t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }


    @Override
    public String parentNames(String id) {
        StringBuffer names = new StringBuffer();
        OrgTree tree = orgTreeMapper.selectOrgTreeById(id);
        if (null != tree) {
            OrgTree eg = new OrgTree();
            String[] parentIds = tree.getAncestors().split(",");
            eg.getParams().put("ids", parentIds);
            List<OrgTree> trees = orgTreeMapper.selectOrgTreeList(eg);
            if (trees.size() > 0) {
                for (int i = 0; i < parentIds.length; i++) {
                    String parentId = parentIds[i];
                    List<OrgTree> collect = trees.stream().filter(item -> item.getId().equals(parentId)).collect(Collectors.toList());
                    if(null != collect && collect.size() > 0){
                        names.append(collect.get(0).getName());
                        names.append(",");
                    }
                }
            }
            names.append(tree.getName());
        }
        return names.toString();
    }

}
